<template>
  <div ref="imageWrapper">
    <a-card title="查询条件" class="search">
      <!-- 查询区域 -->
      <div class="table-page-search-wrapper">
        <a-form-model ref="ruleForm" :model="queryParam" :rules="rules" layout="inline" @keyup.enter.native="onSearch">
          <a-row :gutter="24">
            <a-col :md="6" :sm="6">
              <a-form-model-item label="账套/核算单元" prop="accName">
                <a-input v-model="queryParam.accName" readOnly placeholder="请选择" @click.native="openOrganModel" />
              </a-form-model-item>
            </a-col>
            <a-col :md="6" :sm="6">
              <a-form-model-item label="任期时间" prop="arrayTime">
                <a-range-picker v-model="queryParam.arrayTime" format="yyyy-MM-DD" value-format="yyyy-MM-DD"
                  @change="handleDatechange" />
              </a-form-model-item>
            </a-col>
            <a-col :md="6" :sm="6">
              <a-button type="primary" style="margin-left: 10px; background-color: #000e89; border: 1px solid #000e89"
                @click="ShowItemOfIndicator">指标筛选</a-button>
              <a-button type="primary" icon="download" style="margin-left: 20px" @click="download">导出</a-button>
            </a-col>
            <a-col :md="6" :sm="6">
              <span style="float: right" class="table-page-search-submitButtons">
                <a-button type="primary" @click="onSearch" icon="search" class="yellow_search_btn">查询</a-button>
                <a-button @click="searchReset" icon="reload" class="clear_btn">清除条件</a-button>
                <a-button type="danger" :loading="ydLoading" icon="arrow-right" style="margin-left: 18px"
                  @click="handleToYD(false)">转疑点</a-button>
                <a-button v-if="isBackButton" type="primary" style="margin-left: 8px" @click="backUppage">
                  返回
                </a-button>
              </span>
            </a-col>
          </a-row>
        </a-form-model>
      </div>
    </a-card>
    <!-- 图表 -->
    <a-card style="margin-top: 20px" v-if="series.length != 0">
      <div style="height: 350px; overflow: visible">
        <AssessmentTerm :xAxisData="xAxisData" :series="series" :legendData="legendData" />
      </div>
    </a-card>
    <a-card style="margin-top: 20px">
      <div slot="title">
        <a-tooltip overlayClassName="bgc_tooltip" placement="topRight">
          <template slot="title">
            <span>{{ DataModel.mxms }}</span>
          </template>
          <span style="font-weight: bold">{{ DataModel.modelName || '任期考核指标信息' }}</span>
        </a-tooltip>
        <a-icon type="strikethrough" @click.stop="showImg" />
      </div>
      <a-table v-if="dataSource != []" :columns="columns" :data-source="dataSource" rowKey="id" :pagination="false"
        :loading="loading" :scroll="{ x: aotuScrollX }" :row-selection="rowSelection" class="antableClass">
        <div slot="customTitle" style="position: relative">
          <div style="position: absolute; top: 14px; left: -55px">指标</div>
          <div style="position: absolute; top: -11px; left: 46px; width: 30px">年度</div>
          <div style="
              content: '';
              position: absolute;
              width: 1px;
              height: 167px;
              top: -74px;
              left: 0px;
              background-color: rgb(200 207 211);
              display: block;
              transform: rotate(-71deg);
              box-sizing: border-box;
            ">
          </div>
        </div>
        <template slot="zf" slot-scope="text, record"><span :style="{ color: record.ck }">{{ text }}</span></template>
        <template slot="mzf" slot-scope="text, record"><span :style="{ color: record.mck }">{{ text }}</span></template>
      </a-table>
    </a-card>
    <CheckOrganModal ref="departModal" @ok="updateQueryParam" />
    <BusinessChart ref="businesschart" :flowimg="flowimg" />
    <YDModel ref="YDModel" :router-data="$route.path" />
    <ItemsOfIndicator ref="itemsofindicator" @save="editIndicator" />
  </div>
</template>


<script>
import { JeecgListMixin } from '@/mixins/JeecgListMixin'
import { httpAction, getAction, postAction, deleteAction, putAction } from '@/api/manage'
import CheckOrganModal from '../../../sjxmzygl/yzzx/testcomponent/CheckOrganModal'
import ItemsOfIndicator from './ItemsOfIndicator.vue'
import BusinessChart from './BusinessChart'
import AssessmentTerm from './AssessmentTerm.vue'
import { base64toImg } from '@/mixins/base64toImg'
import YDModel from './YDModel'
import columns from './columns'
import html2canvas from 'html2canvas'
import jumpConfigMixin from '@/views/sj/sjxmzygl/sjxmss/jumpConfigMixin'
import { beforeyearYMD, currentYMD } from '@/mixins/commontime.js'
export default {
  components: { CheckOrganModal, BusinessChart, YDModel, AssessmentTerm, ItemsOfIndicator },
  mixins: [JeecgListMixin, base64toImg, jumpConfigMixin],
  data() {
    return {
      queryParam: {
        unitId: '',
        accName: '',
        endTime: currentYMD(),
        startTime: beforeyearYMD(3, 'years'),
        id: '67e29f69f20b43ace3e578edbb6bccf6',
        extraFlag: false,
        arrayTime: [beforeyearYMD(3, 'years'), currentYMD()],
        modelId: '67e29f69f20b43ace3e578edbb6bccf6',
      },
      url: {
        list: '/sjmx/queryRqkhzb',
        model: '/dataModel/queryDataModelTemplateByExtra',
        // 查询模型筛选项信息
        indicator: '/sjmx/sjModelFieldConfig/queryModelField',
        // 设置模型筛选项信息
        editIndicator: '/sjmx/sjModelFieldConfig/edit',
        // 导出任期考核指标
        export: '/sjmx/exportRqkhzb',
        // 查询模型转疑点信息(多选)
        TurnSuspects: '/sjmx/queryModelMsgMulti',
      },
      rules: {
        accName: [{ required: true, message: '请选择账套/核算单元', trigger: 'change' }],
        arrayTime: [{ required: true, message: '请选择任期时间' }],
      },
      columns: [],
      dataSource: [],
      DataModel: {},
      flowimg: '',
      // 图标相关数据
      xAxisData: [],
      series: [],
      legendData: [],
      disableMixinCreated: true,
      selectedRows: [],
      selectedRowKeys: [],
      isBackButton: false,
    }
  },
  watch: {
    $route: {
      handler: function (to) {
        if (Object.keys(to.query).length) {
          this.disableMixinCreated = true
          this.selectedRowKeys = to.query.selectedRowKeys.split(' ') || []
          to.query.selectedRowKeys && delete to.query.selectedRowKeys
          this.queryParam = Object.assign(this.queryParam, to.query)
          this.queryParam.arrayTime = to.query.arrayTime.split(',')
          this.$nextTick(() => {
            // 这可能存在问题
            this.onSearch()
          })
        } else if (Object.keys(to.params).length && to.params.from == 'sjxmss') {
          let { accName, unitId } = to.params
          this.queryParam.accName = accName
          this.queryParam.unitId = unitId
          let {endDate,startDate} = JSON.parse(to.params.returnRecord)
          debugger
          this.queryParam.endTime =  endDate
          this.queryParam.startTime = startDate
          this.queryParam.arrayTime =[startDate,endDate]
          this.$nextTick(() => {
            // 这可能存在问题
            this.onSearch()
          })
          this.isBackButton = true
          this.returnRecord = to.params.returnRecord
        }
      },
      immediate: true,
    },
  },
  computed: {
    aotuScrollX() {
      return (this.columns.length - 10) * 130 + 1000
    },
    // 行选择
    rowSelection() {
      console.log(this.selectedRowKeys)
      return {
        selectedRowKeys: this.selectedRowKeys,
        onChange: (selectedRowKeys, selectedRows) => {
          this.selectedRowKeys = [...selectedRowKeys]
          this.selectedRows = [...selectedRows]
        },
      }
    },
  },
  methods: {
    searchReset() {
      this.queryParam = {
        unitId: '',
        accName: '',
        endTime: '',
        startTime: '',
        id: '67e29f69f20b43ace3e578edbb6bccf6',
        extraFlag: false,
        modelId: '67e29f69f20b43ace3e578edbb6bccf6',
      }
      this.columns = []
      this.dataSource = []
      this.DataModel = {}
      this.series = []
    },
    updateQueryParam(data, orgId) {
      // console.log('data------>', data)
      let str1 = ''
      let str2 = ''
      let str3 = ''
      data.map((item) => {
        str1 += item.accCode + ','
        str2 += item.accName + ','
        str3 += item.unitId + ','
      })
      if (str1.length > 0) {
        str1 = str1.substr(0, str1.length - 1)
      }
      if (str2.length > 0) {
        str2 = str2.substr(0, str2.length - 1)
      }
      if (str3.length > 0) {
        str3 = str3.substr(0, str3.length - 1)
      }
      this.queryParam.accCode = str1
      this.queryParam.accName = str2
      this.queryParam.unitId = str3
      this.queryParam.extraId = str2
      this.queryParam.orgId = orgId
    },
    loadData(arg) {
      if (!this.url.list) {
        this.$message.error('请设置url.list属性!')
        return
      }
      // 加载数据 若传入参数1则加载第一页的内容
      if (arg === 1) {
        this.ipagination.current = 1
      }
      var params = this.getQueryParams() // 查询条件
      this.loading = true
      this.xAxisData = []
      getAction(this.url.list, params).then((res) => {
        if (res.success) {
          this.dataSource = this.deleteNullObj(res.result.records || res.result)
          const columnsItem = Object.keys(this.dataSource[0])
          this.columns = columns()
          columnsItem.map((item) => {
            if (item != 'id' && item != 'zf' && item != 'zb' && item != 'mzf' && item != 'mck' && item != 'ck') {
              this.columns.splice(this.columns.length - 2, 0, {
                title: item + '年',
                dataIndex: item,
                align: 'center',
              })
              // 给图表x轴坐标数据
              this.xAxisData.push(item)
            }
          })
          // 处理echarts需要的数据
          this.series = this.handleEchartsData(res.result.records || res.result)
          if (res.result.total) {
            this.ipagination.total = res.result.total
          } else {
            this.ipagination.total = 0
          }
        }
        if (res.code === 510) {
          this.$message.warning(res.message)
        }
        this.loading = false
      })
    },
    onSearch() {
      this.series = []
      this.$refs.ruleForm.validate((value) => {
        console.log(value)
        if (value) {
          this.loadData(1)
          this.getModelData()
        }
      })
    },
    openOrganModel() {
      this.$refs.departModal.edit()
    },
    deleteNullObj(arr) {
      for (let i = 0; i < arr.length; i++) {
        if (JSON.stringify(arr[i]) == '{}') {
          arr.splice(i, 1)
          i--
        }
      }
      return arr
    },
    getModelData() {
      this.loading = true
      getAction(this.url.model, this.queryParam).then((res) => {
        if (res.success) {
          this.DataModel = res.result[0]
        }
        if (res.code === 510) {
          this.$message.warning(res.message)
        }
        this.loading = false
      })
    },
    showImg() {
      if (Object.keys(this.DataModel).length != 0) {
        this.flowimg = `${window._CONFIG['domianURL']}/sys/common/static/${this.DataModel.mxUrl}`
        this.$refs.businesschart.show()
      } else this.$message.warning('请先配置查询条件')
    },
    handleDatechange(dates) {
      this.queryParam.startTime = dates[0]
      this.queryParam.endTime = dates[1]
    },
    handleToYD(record) {
      if (this.dataSource.length) {
        const { startTime = '', endTime = '' } = this.queryParam
        let param = Object.assign({}, this.queryParam, {
          selectedRowKeys: this.selectedRowKeys.join(' '),
        })
        let ydnr = undefined
        let gzzd = undefined
        // if (record) {
        //   ydnr = `【科目代码：${record.subjectCode}】【科目名称：${record.subjectName}】`
        // }
        let time = `【${startTime}～${endTime}】【任期考核指标模型】`
        let ydList = JSON.stringify(this.selectedRows)
        postAction(this.url.TurnSuspects, Object.assign({}, this.queryParam, { ydList: ydList })).then((res) => {
          if (res.success) {
            if (res.result.length) {
              ydnr = res.result[0].ydms ? res.result[0].ydms : ydnr
              gzzd = res.result[0].gzzd ? res.result[0].gzzd : gzzd
            }
            this.addYd(param, ydnr, time, gzzd)
          }
          if (res.code === 510) {
            this.$message.warning(res.message)
          }
        })
      } else {
        this.$message.error('空数据不能新建疑点')
      }
    },
    addYd(record, ydnr, time, gzzd) {
      this.ydLoading = true
      html2canvas(this.$refs.imageWrapper).then((canvas) => {
        let dataURL = canvas.toDataURL('image/png')
        console.log('父组件调用完了')
        this.$refs.YDModel.show(record, dataURL, ydnr, time, gzzd)
        this.ydLoading = false
      })
    },
    handleEchartsData(data) {
      let result = []
      data.map((item, index) => {
        if (index < data.length - 1) {
          this.legendData.push(item.zb)
          result.push({
            name: item.zb,
            type: 'line',
            tooltip: {
              valueFormatter: function (value) {
                return value + (item.zb.indexOf('率') != -1 ? '%' : '元')
              },
            },
            yAxisIndex: item.zb.indexOf('率') != -1 ? 1 : 0,
            data: this.getItemData(item),
          })
        }
      })
      return result
    },
    getItemData(item) {
      //获取每条数据中 每年的数据
      let yearsData = []
      this.xAxisData.map((year) => {
        yearsData.push(Number.parseInt(item[year]))
      })
      return yearsData
    },
    // 展示模型筛选项信息
    ShowItemOfIndicator() {
      this.GetItemOfIndicator()
    },
    // 查询模型筛选项信息
    GetItemOfIndicator() {
      getAction(this.url.indicator, this.queryParam).then((res) => {
        if (res.success) {
          let projectItem = Object.assign({}, JSON.parse(res.result.projectJson))
          this.$refs.itemsofindicator.edit(projectItem)
        }
        if (res.code === 510) {
          this.$message.warning(res.message)
        }
        this.loading = false
      })
    },
    // 保存已经修改的projectJson(子组件返回json串)
    editIndicator(projectJson) {
      putAction(this.url.editIndicator, Object.assign({}, this.queryParam, { projectJson })).then((res) => {
        console.log(res)
      })
    },
    // 导出表格
    download() {
      if (this.dataSource.length != 0) {
        getAction(this.url.export, this.queryParam).then((res) => {
          if (res.success) {
            this.handleDownloadFile(res.result)
          }
        })
      } else {
        this.$message.warning('请先查询')
      }
    },
    handleDownloadFile(fileUrl) {
      this.$message.success('正在下载，请稍等！')
      let url = `${window._CONFIG['domianURL']}/sys/common/download/${fileUrl}`
      window.open(url, '_blank')
    },
  },
}
</script>
<style lang="less">
.bgc_tooltip {
  .ant-tooltip-inner {
    // 这里是框框
    border-radius: 20px;
    color: #333;
    width: 400px;
    padding: 10px 15px;
    background-color: rgba(255, 255, 255, 0.8) !important;
  }

  .ant-tooltip-arrow::before {
    // 这里是小三角形
    background-color: #fff !important;
  }
}
</style>
<style lang="less" scoped>
@import '~@assets/less/tableTheme.less';

.ant-table-fixed-left .ant-table-thead>tr>th:last-child {
  border-top-right-radius: 0;
  background-color: red;
  padding: 0;
}
</style>
